package com.atguigu.delivery.servlet;

import com.atguigu.delivery.entity.Delivery;
import com.atguigu.delivery.entity.SysUser;
import com.atguigu.delivery.service.api.DeliveryService;
import com.atguigu.delivery.service.impl.DeliveryServiceImpl;
import com.atguigu.delivery.util.DeliveryConstant;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet (urlPatterns = "/DeliveryServletSave")
public class DeliveryServletSave extends HttpServlet {

    private DeliveryService deliveryService = new DeliveryServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1、获取表单提交的请求参数
        String deliveryName = request.getParameter("user_name");
        String companyId = request.getParameter("cat_id");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String sendTime = request.getParameter("date");
        String state = request.getParameter("state");

        // 2、把接收到的请求参数，封装为 Delivery 对象
        Delivery delivery =
                new Delivery(null, deliveryName, null, Integer.parseInt(companyId), phone, address, sendTime, Integer.parseInt(state), null);

        // 3、从会话域读取用户的登录状态
        HttpSession session = request.getSession();
        SysUser sysUser = (SysUser) session.getAttribute(DeliveryConstant.ATTR_NAME_LOGIN_USER);
        Integer userId = sysUser.getId();
        delivery.setUserId(userId);

        // 4、调用 Service 方法执行保存
        deliveryService.saveDelivery(delivery);

        // 5、重定向回到列表页面
        response.sendRedirect("/DeliveryServletList");
    }
}
